<template>
  <Modal
    v-model="showCreateProjectModal"
    title="创建项目"
    width="950"
    :mask-closable="false"
    @on-cancel="handleCreateProjectCancel"
  >
    <Tabs name="project-add-tabs" :animated="true">
      <TabPane label="基础信息" tab="project-add-tabs">
        <Form
          label-position="right"
          :label-width="110"
          ref="projectForm"
          :model="projectForm"
          :rules="projectValidate"
        >
          <FormItem label="项目名称" prop="name">
            <Input clearable v-model="projectForm.name" />
          </FormItem>
          <FormItem label="运行环境" prop="environments">
            <Select v-model="projectForm.environments" clearable multiple>
              <Option
                v-for="item in environments"
                :value="item.id"
                :key="item.id"
                :label="item.base_url"
              >
                <span>{{ item.name }}</span>
                <span style="float: right; color: #ccc">{{
                  item.base_url
                }}</span>
              </Option>
            </Select>
          </FormItem>
          <FormItem label="默认运行环境" prop="default_environment">
            <RadioGroup v-model="projectForm.default_environment">
              <Radio
                v-for="item in selectedEnvs"
                :key="item.id"
                :label="item.id"
                >{{ item.name }}</Radio
              >
            </RadioGroup>
          </FormItem>
          <FormItem label="项目成员" prop="members">
            <Select v-model="projectForm.members" clearable multiple>
              <Option v-for="item in members" :value="item.id" :key="item.id">
                <span>{{ item.username }}</span>
                <span style="float: right; color: #ccc">{{
                  item.real_name
                }}</span>
              </Option>
            </Select>
          </FormItem>
          <FormItem label="备注">
            <Input
              type="textarea"
              clearable
              v-model="projectForm.remark"
              :rows="10"
            />
          </FormItem>
        </Form>
      </TabPane>
      <TabPane label="全局参数配置" tab="project-add-tabs">
        <JsonEditor
          v-model="projectForm.global_variables"
          jsonEditorId="createProjectGlobalVariables"
          style="height: 500px"
        ></JsonEditor>
      </TabPane>
    </Tabs>
    <div slot="footer">
      <Button type="default" @click="handleCreateProjectCancel">取消</Button>
      <Button type="primary" @click="handleCreateProjectSubmit('projectForm')"
        >确定</Button
      >
    </div>
  </Modal>
</template>

<script>
import JsonEditor from "_c/json-editor";
import { createProject } from "@/api/HttpAutoTestService/project";
import { getEnvNames } from "@/api/HttpAutoTestService/environment";
import { getUserNames } from "@/api/HttpAutoTestService/user";

export default {
  name: "project-create",
  components: {
    JsonEditor,
  },

  props: {
    createProject: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    createProject(val) {
      if (val) {
        getEnvNames().then((res) => {
          this.environments = res.data;
        });

        getUserNames().then((res) => {
          this.members = res.data;
        });
      }
    },
  },
  computed: {
    showCreateProjectModal: {
      get() {
        return this.createProject;
      },
      set(val) {
        this.$emit("update:createProject", val);
      },
    },

    selectedEnvs() {
      let environments = this.environments.filter((item) =>
        this.projectForm.environments.includes(item.id)
      );

      if (environments.length === 1) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.projectForm.default_environment = environments[0].id;
      }
      return environments;
    },
  },
  data() {
    const validateEnvironments = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error("请选择项目环境"));
      }
      callback();
    };
    const validateMembers = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error("请选择项目成员"));
      }
      callback();
    };
    return {
      projectForm: {
        name: "",
        members: [],
        environments: [],
        default_environment: "",
        remark: "",
        global_variables: {},
      },
      projectValidate: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        default_environment: [
          { required: true, message: "请选择默认运行环境", trigger: "change" },
        ],
        environments: [
          {
            required: true,
            validator: validateEnvironments,
            trigger: "change",
          },
        ],
        members: [
          { required: true, validator: validateMembers, trigger: "change" },
        ],
      },
      environments: [],
      members: [],
    };
  },
  methods: {
    handleCreateProjectCancel() {
      this.showCreateProjectModal = false;
      this.projectForm = {
        name: "",
        members: [],
        environments: [],
        default_environment: "",
        remark: "",
        global_variables: {},
      };
      this.$emit("initProjectTable");
      this.$refs['projectForm'].resetFields();
    },

    handleCreateProjectSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.projectForm.global_variables === "") {
            this.projectForm.global_variables = {};
          }

          createProject(this.projectForm)
            .then((res) => {
              if (res.status === 201) {
                this.$Message.info("创建成功");
                this.handleCreateProjectCancel();
              } else {
                this.$Message.error("创建失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
